package com.app.controller.importExcel;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 试验任务：导入
 */
@Slf4j
@RestController
@Controller
@RequestMapping("/api/import")
public class TestTaskImportController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private PersonService personService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TestsMapper testsMapper;
    @Autowired
    private TestsRecordMapper testsRecordMapper;

    //型号信息导入
    @PostMapping("/importType")
    public Result<Object> importType(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        cn.hutool.poi.excel.ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "number");
        reader.addHeaderAlias("型号名称", "name");
        reader.addHeaderAlias("所属单位", "departmentText");
        reader.addHeaderAlias("作战使命", "operationalMission");
        reader.addHeaderAlias("攻击目标", "attackTarget");
        reader.addHeaderAlias("作战使用方式", "operationalMode");
        reader.addHeaderAlias("制导方式", "guidanceMode");
        reader.addHeaderAlias("适应载机", "adaptiveCarrier");
        reader.addHeaderAlias("发射条件", "launchingCondition");
        reader.addHeaderAlias("发射方式", "launchingMode");
        reader.addHeaderAlias("射程", "ranges");
        reader.addHeaderAlias("速度", "speed");
        reader.addHeaderAlias("目标高度范围", "altitude");
        reader.addHeaderAlias("命中精度", "hitAccuracy");
        reader.addHeaderAlias("末端约束条件", "restraint");
        reader.addHeaderAlias("RCS", "rcs");
        reader.addHeaderAlias("导引头抗干扰能力", "seeker");
        reader.addHeaderAlias("卫星定位系统抗干扰能力", "satellite");
        reader.addHeaderAlias("机动能力", "maneuver");
        reader.addHeaderAlias("目标适应性", "goal");
        reader.addHeaderAlias("引信", "fuze");
        reader.addHeaderAlias("战斗部", "warhead");
        reader.addHeaderAlias("尺寸、重量", "dimension");
        //reader.read(标头行数，开始行数，对象)
        List<TypeModel> typeModelList = reader.read(0, 0, TypeModel.class);
        for (int i = 0; i < typeModelList.size(); i++) {
            TypeModel typeModel = typeModelList.get(i);
            DepartmentModel departmentModel = departmentService.getdepByName(typeModel.getDepartmentText());
            if (departmentModel != null) {
                typeModel.setDepartmentId(departmentModel.getId());
//                int row = i + 3;
//                return Result.error(500, "第" + row + "行单位不存在");
            }
            typeModel.setCreateTime(CommonHelp.getNowTimestamp());
            try {
                typeService.insert(typeModel);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500, "导入失败");
            }
        }
        return Result.success("");
    }


    //试验信息导入
    @PostMapping("/importTests")
    public Result<Object> importTest(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("序号", "number");
        reader.addHeaderAlias("年度", "year");
        reader.addHeaderAlias("型号", "modelUnit");
        reader.addHeaderAlias("单位", "departmentName");
        reader.addHeaderAlias("试验类型", "testType");
        reader.addHeaderAlias("试验科目", "testSubject");
        reader.addHeaderAlias("日期", "testTime");
        reader.addHeaderAlias("试验条件", "testCondition");
        reader.addHeaderAlias("试验结果", "testResult");
        reader.addHeaderAlias("故障处理", "testFault");
        reader.addHeaderAlias("故障分析定位", "testFaultAnalysis");
        reader.addHeaderAlias("解决方式", "faultSolution");
        reader.addHeaderAlias("归零评审日期", "reviewTime");
        reader.addHeaderAlias("遗留问题", "remainingProblems");
        reader.addHeaderAlias("改进意见建议", "recommendation");
        //reader.read(标头行数，开始行数，对象)
        List<TestsRecordModel> testsRecordModel = reader.read(4, 5, TestsRecordModel.class);
        for (int i = 0; i < testsRecordModel.size(); i++) {
            TestsRecordModel testsRecord = testsRecordModel.get(i);
            DepartmentModel departmentModel = departmentService.getdepByName(testsRecord.getDepartmentName());
            if (departmentModel != null) {
                testsRecord.setDepartmentId(departmentModel.getId());
            }
            testsRecord.setCrtTime(CommonHelp.getNowTimestamp());
            try {
                testsRecordMapper.insert(testsRecord);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500, "导入失败");
            }
        }
        return Result.success("");
    }

    /**
     * 试验信息批量插入
     *
     * @throws IOException
     */
    public String insertTest(List<TestsModel> TestsList) throws IOException {
        TestsPersonModel testsPersonModel = new TestsPersonModel();
        if (TestsList != null && !TestsList.isEmpty()) {
            for (int i = 0; i < TestsList.size(); i++) {
                if (TestsList.get(i) != null && TestsList.get(i).getName() != null) {
                    String contacts = TestsList.get(i).getPersonName();
                    String contactInformation = TestsList.get(i).getPhone();
                    PersonModel personModel = personService.selectByName(contacts, contactInformation);
                    if (personModel != null) {
                        testsPersonModel.setPersonId(personModel.getId());
                    }
                    String departmentName = TestsList.get(i).getDepartmentName();
                    DepartmentModel departmentModel = departmentService.getdepByName(departmentName);
                    if (departmentModel != null) {
                        TestsList.get(i).setDepartmentId(departmentModel.getId());
                        TestsList.get(i).setCreateTime(CommonHelp.getNowTimestamp());
                    }
                }
            }
        }
        try {
            testsMapper.batchInsertTest(TestsList);
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败";
        }
        assert TestsList != null;
        return "试验信息成功导入" + TestsList.size() + "行。";
    }
}
